class Solution {
public:
    unordered_map<int, vector<int>> ma;
    int m1[20005], m2[20005], mi[20005];
    vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
        for (auto& x : edges)
        {
            ma[x[0]].push_back(x[1]);
            ma[x[1]].push_back(x[0]);
        }
        dfs1(0, -1);
        for (auto& x : ma[0])
        {
            dfs2(x, 0);
        }
        int temp = 1000000;
        vector<int> ans;
        for (int i = 0; i < n; i++) temp = min(temp, m1[i]);
        for (int i = 0; i < n; i++)
        {
            if (m1[i] == temp) ans.push_back(i);
        }
        return ans;
    }
    int dfs1(int pos, int pre)
    {
        int ans1 = 0, ans2 = 0;
        for (auto& x : ma[pos])
        {
            if (x == pre) continue;
            int temp = dfs1(x, pos);
            if (temp > ans1)
            {
                ans2 = ans1;
                ans1 = temp;
                mi[pos] = x;
            }
            else if (temp > ans2)
            {
                ans2 = temp;
            }
        }
        m1[pos] = ans1 + 1;
        m2[pos] = ans2 + 1;
        return ans1 + 1;
    }
    void dfs2(int pos, int pre)
    {
        int temp;
        if (mi[pre] == pos) temp = m2[pre] + 1;
        else temp = m1[pre] + 1;
        if (temp > m1[pos])
        {
            mi[pos] = pre;
            m2[pos] = m1[pos];
            m1[pos] = temp;
        }
        else if (temp > m2[pos])
        {
            m2[pos] = temp;
        }
        for (auto& x : ma[pos])
        {
            if (x == pre) continue;
            dfs2(x, pos);
        }
    }
};